<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 搜索与添加 -->
      <el-row :gutter="20">
        <el-col :span="14">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            clearable
            v-model="queryInfo.query"
            @clear="clearInput"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addUserItem">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <!-- 状态 -->
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="showEditUser(scope.row.id)"
            ></el-button>

            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="deleteUserDialg(scope.row.id)"
            ></el-button>

            <el-tooltip effect="dark" content="设置" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" circle @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 用户添加 -->

    <el-dialog title="添加新用户" :visible.sync="addUserVisible" width="50%">
      <el-form
        :model="addUserForm"
        :rules="addUserRules"
        ref="addUserRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser(addUserForm.id)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 用户修改页面呈现 -->
    <el-dialog title="用户修改页面" :visible.sync="editUserVisible" width="50%">
      <el-form
        :model="editUserForm"
        ref="addUserRef"
        :rules="editUserRules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmEdit()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除按钮的弹框 -->
    <!-- 分配角色按钮 -->
    <el-dialog title="分配角色" :visible.sync="dialogVisible" width="30%" @close="setRoleDialogClosed">
      <p>用户名：{{userInfo.username}}</p>
      <p>用户邮箱：{{userInfo.email}}</p>
      <el-select v-model="userSelectId" placeholder="请选择">
        <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subAddRole(userInfo.id)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    var validateEamil = (rule, value, clb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return clb()
      }
      clb('请输入正确的邮箱')
    }
    var validateMobile = (rule, value, clb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return clb()
      }
      clb('请输入正确的电话')
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      inputData: '',
      addUserVisible: false,
      addUserForm: {
        username: '',
        email: '',
        password: '',
        mobile: ''
      },
      editUserForm: {},

      editUserVisible: false,

      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEamil, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ]
      },
      editUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEamil, trigger: 'blur' }
        ],

        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ]
      },
      //分配角色对话框

      dialogVisible: false,
      //用户信息
      userInfo: {},
      //当前用户选中的角色id
      userSelectId: '',
      //角色列表
      roleList: []
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    //分配权限展示页面
    async setRole(userInfo) {
      this.userInfo = userInfo
      this.dialogVisible = true
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
    },
    //分配角色提交
    async subAddRole() {
      if (!this.userSelectId) {
        return this.$message.error('请选择需要分配的角色')
      }
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.userSelectId
        }
      )
      //
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败')
      }
      this.$message.success('更新角色成功')
      this.dialogVisible = false
      this.getUserList()
    },
    //
    setRoleDialogClosed() {
      //当关闭对话框的时候，重置下拉框中的内容
      this.userSelectId = ''
      this.userInfo = {}
    },
    // 获取列表信息   //查询
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      console.log(res)

      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    //分页显示
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    //修改用户状态
    async userStateChange(data) {
      const { data: res } = await this.$http.put(
        `users/${data.id}/state/${data.mg_state}`
      )
      // console.log(res)
      //用户id
      this.userSelectId = res.id
      if (res.meta.status !== 200) {
        data.mg_state != data.mg_state
        this.$message.error('设置状态失败')
        return
      }
      this.$message.success('设置状态成功')
    },
    //清空数据,获取列表
    clearInput() {
      this.getUserList()
    },
    //添加用户按钮
    addUserItem() {
      this.addUserVisible = true
    },
    //添加用户确认按钮
    addUser() {
      //预校验
      this.$refs.addUserRef.validate(async valid => {
        // console.log(valid)
        if (!valid) {
          this.$message.error('添加用户失败')
          return
        }
        const { data: res } = await this.$http.post('users', this.addUserForm)
        // console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户列表失败')
        }
        this.$message.success('添加用户列表成功')
        //关闭对话框
        this.addUserVisible = false
        this.getUserList()
      })
    },
    //用户信息（id、）查询
    async showEditUser(id) {
      console.log(id)
      // 请求数据渲染页面
      const { data: res } = await this.$http.get('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('请求数据失败')
        return
      }
      this.$message.success('请求数据成功')
      this.editUserForm = res.data
      this.editUserVisible = true
    },
    //提交修改
    async confirmEdit() {
      const { data: res } = await this.$http.put(
        'users/' + this.editUserForm.id,
        this.editUserForm
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('修改数据失败')
        return
      }
      this.$message.success('修改数据成功')
      this.editUserVisible = false
      this.getUserList()
    },
    //删除用户
    // async deleteUser(id) {
    //   const { data: res } = await this.$http.delete('users/' + id)

    //   if (res.meta.status !== 200) {
    //     this.$message.error('删除数据失败')
    //     return
    //   }
    //   this.$message.success('删除数据成功')
    //   this.editUserVisible = false
    //   this.getUserList()
    // },
    //删除按钮的弹框
    deleteUserDialg(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('users/' + id)
          if (res.meta.status !== 200) {
            this.$message.error('删除数据失败')
            return
          }
          this.$message.success('删除数据成功')
          this.editUserVisible = false
          this.getUserList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>
<style lang='less'scoped>
</style>